// pages/list/list.js
 
Page({
 
  data: {
       hiddenBlean1:true,
       hiddenBlean2:false,
       userInfo:'',//用户信息
       nickName:'',//用户姓名
       avatarUrl:'',//用户头像地址
       m:0,//用户的登录状态
       swiperList:[],
  }, 
  onShow:function () {
    this.getSwiperList();
  },
  getSwiperList :function(){
    wx.request({
      url: 'http://8.138.155.196:3000/users/api/communitypicture',
      method:'GET',
      success:(res)=>{
        console.log(res)
        this.setData({
          swiperList:res.data.data
        })
      }
    })
  },
  onLoad: function (options) {
   
    console.log(this.data.userInfo);
    //从缓存中获取用户信息
    var userInfo = wx.getStorageSync('userinfo');
    this.setData({
      userInfo:userInfo
    })
  },
//获取用户信息

  getUserProfile:function() {
    if(this.data.m===0) {
      wx.getUserProfile({
        desc: '登陆后使用全部功能',
        success:(res)=> {
          let user = res.userInfo
          console.log('获取成功',res)
          
          wx.setStorage({
            data: res.userInfo,
            key:'userInfo',
          });
 
           // 获取全局实例并更新 globalData
           let appInstance = getApp();
           appInstance.globalData.userInfo = user;
           
          wx.login({//获取code向后端发送并请求token
            success(res) {
              console.log(res.code)
              let code = res.code     
              wx.request({
                url: 'http://8.138.155.196:3000/users/wx/login',
                method:'POST',
                header: {
                    'Content-Type':'application/json'
                },
                data: {code: code},
                success:res=>{
                  let token;   
                   console.log(res)
                   console.log(res.data)
                   wx.setStorageSync('token', res.data)
                   console.log('token');
                }
              })
            }
          });
        console.log('用户信息',res.userInfo),
        console.log(res.userInfo.nickName),
          this.setData({
            m:1,
            nickName : res.userInfo.nickName,
            avatarUrl: res.userInfo.avatarUrl,
            hiddenBlean2:true,
            hiddenBlean1:false
          })
          wx.showToast({
            title: '登陆成功',
          })
          wx.hideToast()
          wx.switchTab({
            url: '/pages/home/home' // 假设主页面是 pages/home/home
          });
        },
        fail:(res)=> {
          console.log('授权失败',res)
        }
      })
    }
    else {
      wx.showToast({
        title: '您已经登录了',
      })
    }
},
//退出登录
loginOut() {
  this.setData({
    userInfo:'',
    hiddenBlean1:true,
    hiddenBlean2:false,
    m:0
  })
  wx.request({
    url: 'http://8.138.155.196:3000/users/wx/login',
    method:'POST',
    header: {
      'Content-Type':'application/json'
    },
    success:res=> {
      console.log(res)
    }
  })
  wx.setStorageSync('user', null),
  wx.showToast({
    title: '已退出登录',
  })
}
})
